﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Net;
using System.IO;
using HtmlAgilityPack;
using Odds.Entity;
using System.Text.RegularExpressions;
using System.Reflection;
using Odds.Business;
using JJY.CommonHelper;
using Odds.DataAccess;

public partial class BetCollection : System.Web.UI.Page
{
    //string testUrl = "http://sports.sina.com.cn/l/2010-10-27/10165272421.shtml";

    protected void Page_Load(object sender, EventArgs e)
    {
    }


    protected void btnSumit_Click(object sender, EventArgs e)
    {
        //string str = GetSource(TextBox1.Text).Trim();
        MatchDataOrganizeMonitor d = new MatchDataOrganizeMonitor(txtUrl.Text);

        OddsCompanyController oddsCompanyController = new OddsCompanyController();
        Dictionary<string, Guid> dicOddsCompany = oddsCompanyController.Insert(d._OddsCompanySet);
        //Dictionary<string, Guid> dicOddsCompany = oddsCompanyController.GetOddsCompanyDictionary();

        OddsTeamController oddsTeamController = new OddsTeamController();
        Dictionary<string, Guid> dicOddsTeam = oddsTeamController.Insert(d._OddsTeamSet);
        //Dictionary<string, Guid> dicOddsTeam = oddsTeamController.GetOddsTeamDictionary();

        OddsMatchTypeController oddsMatchTypeController = new OddsMatchTypeController();
        Dictionary<string, Guid> dicOddsMatchType = oddsMatchTypeController.Insert(d._OddsMatchTypeSet);
        //Dictionary<string, Guid> dicOddsMatchType = oddsMatchTypeController.GetMatchTypeDictionary();

        OddsIssueController oddsIssueController = new OddsIssueController();
        KeyValuePair<string, Guid> oddsIssue = oddsIssueController.Insert(d._OddsIssue).FirstOrDefault();

        OddsIssueHtmlController oddsIssueHtmlController = new OddsIssueHtmlController();
        oddsIssueHtmlController.Insert(d._OddsIssueHtml);


        List<OddsIssueItem> oddsIssueItemSet = new List<OddsIssueItem>();
        List<OddsValue> oddsValueSet = new List<OddsValue>();

        foreach (OddsTableRecorder recorder in d._OddsTableRecoderSet)
        {            
            if (!oddsIssueItemSet.Any(i => i.IndexInIssue == recorder.IndexInIssue))
            {
                Guid guid = Guid.NewGuid();
                oddsIssueItemSet.Add(new OddsIssueItem()
                {
                    IssueItemID = guid,
                    IssueID = oddsIssue.Value,
                    IndexInIssue = recorder.IndexInIssue,
                    HomeTeamID = dicOddsTeam[recorder.HomeTeam],
                    VisitingTeamID = dicOddsTeam[recorder.VisitingTeam],
                    MatchTypeID = dicOddsMatchType[recorder.MatchType],
                    MatchResult = -1
                });
            }
        }

        OddsIssueItemController oddsIssueItemController = new OddsIssueItemController();
        Dictionary<int,Guid> dicOddsIssueItem = oddsIssueItemController.Insert(oddsIssueItemSet);

        foreach (OddsTableRecorder recorder in d._OddsTableRecoderSet)
        {
            oddsValueSet.Add(new OddsValue()
            {                
                IssueItemID = dicOddsIssueItem[recorder.IndexInIssue],
                IndexInIssueItem = recorder.OddsIndexInIssueItem,
                CompanyID = dicOddsCompany[recorder.OddsCompany.ToLower()],
                OddsDatetime = recorder.OddsPublishDateTime,
                OddsWin = recorder.OddsWin,
                OddsDraw = recorder.OddsDraw,
                OddsLose =recorder.OddsLose
            });
        }


        OddsValueController oddsValueController = new OddsValueController();
        oddsValueController.Insert(oddsValueSet);

        tdInfo.InnerText = string.Format("Issue {0} data collection succesful!", d._OddsIssue.IssueRealID.ToString());
    }

    /*
    protected void btnSumit_Click(object sender, EventArgs e)
    {
        //string str = GetSource(TextBox1.Text).Trim();


        string strUrl = txtUrl.Text;

        const string tableTitleID = "artibodyTitle";
        const string tableID = "artibody";
        const string inputPublishDateID = "pub_date";
        string EmptyString = string.Empty;

        OddsIssue oddsIssue = new OddsIssue();
        OddsIssueHtml oddsIssueHtml = new OddsIssueHtml();
        List<OddsTableRecorder> oddsTableRecorderSet = new List<OddsTableRecorder>();
        List<OddsCompany> oddsCompanySet = new List<OddsCompany>();
        List<OddsTeam> oddsTeamSet = new List<OddsTeam>();
        List<OddsMatchType> oddsMatchTypeSet = new List<OddsMatchType>();

        int issueID = 0;
        DateTime publishDate = DateTime.Parse("1900-1-1");
        DateTime oddsDateTime = DateTime.Parse("1900-1-1");
        List<OddsCompany> tempOddsCompanySet = new List<OddsCompany>();

        string str = HttpRequestService.GetHtmlSourceByUrl(strUrl)
            .Replace(@"\t", EmptyString).Replace(@"\r", EmptyString).Replace(@"\n", EmptyString)
            .Replace("&nbsp;", EmptyString).Replace("　", EmptyString).Trim();

        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml(str);

        LogHelper.Infomation("Load html complete.");

        //get issue number from title
        HtmlNode nodeTitleSet = doc.DocumentNode.SelectNodes("//h1[@id='" + tableTitleID + "']")[0];
        int.TryParse(Regex.Matches(nodeTitleSet.InnerText, "\\d{5}")[0].ToString(), out issueID);

        //get publish date, this is also issue end date
        HtmlNode nodePublishDate = doc.DocumentNode.SelectNodes("//span[@id='" + inputPublishDateID + "']")[0];
        DateTime.TryParse(Regex.Matches(nodePublishDate.InnerText, "\\d{4}年\\d{1,2}月\\d{1,2}日")[0].ToString()
            .Replace("年", "-").Replace("月", "-").Replace("日", EmptyString), out publishDate);

        oddsIssue.IssueRealID = issueID;
        oddsIssue.EndDate = publishDate;

        oddsIssueHtml.IssueRealID = issueID;
        oddsIssueHtml.IssueHtml = str;
        oddsIssueHtml.IssueUrl = strUrl;

        LogHelper.Infomation("Get publish complete.");

        //get all the tr from the tabel which include data we need
        HtmlNodeCollection nodeTRSet = doc.DocumentNode.SelectNodes("//div[@id='" + tableID + "']/table/tbody/tr/td/table/tbody/tr");
        if (nodeTRSet == null)
        {
            nodeTRSet = doc.DocumentNode.SelectNodes("//div[@id='" + tableID + "']/table/tr/td/table/tr");
            if (nodeTRSet == null)
            {
                nodeTRSet = doc.DocumentNode.SelectNodes("//div[@id='" + tableID + "']/div/table/tr/td/table/tr");
                if (nodeTRSet == null)
                {
                    nodeTRSet = doc.DocumentNode.SelectNodes("//div[@id='" + tableID + "']/div/table/tbody/tr/td/table/tbody/tr");
                }
            }
        }

        LogHelper.Infomation("Load all tr complete.");

        string matchType = EmptyString;
        string homeTeam = EmptyString, visitingTeam = EmptyString;

        byte indexInIssueItem = 0;//using for ordering oddsitem, normally order by odds time, but order by int is better.
        byte indexInIssue = 0;//using for oddsitem, index of oddsitem in issue
        foreach (HtmlNode nodeTR in nodeTRSet)
        {
            //DateTime oddsDateTime = publishDate;

            HtmlNodeCollection nodeTDSet = doc.DocumentNode.SelectNodes(nodeTR.XPath + "/td");

            //it's odds' company name row
            if (nodeTDSet.Count == 5)
            {
                tempOddsCompanySet.Clear();
                tempOddsCompanySet.Add(new OddsCompany() { CompanyName = nodeTDSet[1].InnerText.Replace(" ", EmptyString).ToLower() });
                tempOddsCompanySet.Add(new OddsCompany() { CompanyName = nodeTDSet[2].InnerText.Replace(" ", EmptyString).ToLower() });
                tempOddsCompanySet.Add(new OddsCompany() { CompanyName = nodeTDSet[3].InnerText.Replace(" ", EmptyString).ToLower() });
                tempOddsCompanySet.Add(new OddsCompany() { CompanyName = nodeTDSet[4].InnerText.Replace(" ", EmptyString).ToLower() });

                foreach (OddsCompany company in tempOddsCompanySet)
                {
                    //LiBo mutil-name check
                    if (company.CompanyName.IndexOf("立博") > -1)
                    {
                        company.CompanyName = "立博";
                    }

                    if (!oddsCompanySet.Any(o => o.CompanyName.ToLower() == company.CompanyName.ToLower()))
                    {
                        oddsCompanySet.Add(company);
                    }
                }
            }

            //it's row include match type
            else if (nodeTDSet.Count == 13)
            {
                matchType = nodeTDSet[0].InnerText.Replace(" ", EmptyString);
                oddsMatchTypeSet.Add(new OddsMatchType()
                {
                    MatchTypeName = matchType
                });
            }
            //it's row include lottery data
            else if (nodeTDSet.Count == 14)
            {
                indexInIssueItem++;

                //the row has IssueItemIndex, which is the odds begin row
                if (!string.IsNullOrEmpty(nodeTDSet[0].InnerText.Trim()) && byte.TryParse(nodeTDSet[0].InnerText.Trim(), out indexInIssue))
                {
                    //set as init time
                    oddsDateTime = DateTime.Parse("1900-1-1");

                    //set this variable = 1 when the first column have number
                    indexInIssueItem = 1;

                    //get home team's name and visiting team's name
                    OddsTeam oddsHomeTeam = new OddsTeam();
                    oddsHomeTeam.TeamName = nodeTDSet[1].InnerText.Split(new string[] { "VS" }, StringSplitOptions.RemoveEmptyEntries)[0]
                        .Replace(" ", EmptyString).Replace("(中立场地)", EmptyString).Replace("(延期)", EmptyString);
                    homeTeam = oddsHomeTeam.TeamName;
                    if (!oddsTeamSet.Any(o => o.TeamName == oddsHomeTeam.TeamName))
                    {
                        oddsTeamSet.Add(oddsHomeTeam);
                    }

                    OddsTeam oddsVisitTeam = new OddsTeam();
                    oddsVisitTeam.TeamName = nodeTDSet[1].InnerText.Split(new string[] { "VS" }, StringSplitOptions.RemoveEmptyEntries)[1]
                        .Replace(" ", EmptyString).Replace("(中立场地)", EmptyString).Replace("(延期)", EmptyString);
                    visitingTeam = oddsVisitTeam.TeamName;
                    if (!oddsTeamSet.Any(o => o.TeamName == oddsVisitTeam.TeamName))
                    {
                        oddsTeamSet.Add(oddsVisitTeam);
                    }
                }
                else
                {
                    //get odds time
                    if (nodeTDSet[1].InnerText.IndexOf("月") > -1)
                    {
                        //sometime publish date and odds date in different month
                        DateTime.TryParse(publishDate.Year.ToString() + "-" +
                              nodeTDSet[1].InnerText.Replace("月", "-").Replace("日", " ").Replace("：", ":"), out oddsDateTime);
                    }
                    else
                    {
                        //some odds time is empty, keep it as 1900-1-1
                        if (nodeTDSet[1].InnerText.Trim() != EmptyString)
                        {
                            string date = publishDate.Year.ToString() + "-" + publishDate.Month.ToString() +
                                "-" + nodeTDSet[1].InnerText.Replace("日", " ").Replace("：", ":");

                            //normally date
                            if (!DateTime.TryParse(date, out oddsDateTime))
                            {
                                //if publish date is 1st.Feb odds date is Jan.31, will parse date like below
                                date = publishDate.Year.ToString() + "-" + publishDate.AddMonths(-1).Month.ToString() +
                                "-" + nodeTDSet[1].InnerText.Replace("日", " ").Replace("：", ":");
                                DateTime.TryParse(date, out oddsDateTime);
                            }
                        }
                    }
                }

                if (indexInIssue > 0)
                {
                    int indexTemp = 0;
                    foreach (OddsCompany oddsCompany in tempOddsCompanySet)
                    {
                        OddsTableRecorder oddsTableRecorder = new OddsTableRecorder()
                        {
                            IssueID = issueID,
                            OddsIndexInIssueItem = indexInIssueItem,
                            IssuePublishDate = publishDate,
                            IndexInIssue = indexInIssue,
                            MatchType = matchType,
                            OddsPublishDateTime = oddsDateTime,
                            HomeTeam = homeTeam,
                            VisitingTeam = visitingTeam,
                        };

                        oddsTableRecorder.OddsCompany = oddsCompany.CompanyName;

                        decimal oddsWin = 0, oddsDraw = 0, oddsLose = 0;
                        if (decimal.TryParse(nodeTDSet[3 * indexTemp + 2].InnerText, out oddsWin))
                        {
                            oddsTableRecorder.OddsWin = oddsWin;
                        }
                        if (decimal.TryParse(nodeTDSet[3 * indexTemp + 3].InnerText, out oddsDraw))
                        {
                            oddsTableRecorder.OddsDraw = oddsDraw;
                        }
                        if (decimal.TryParse(nodeTDSet[3 * indexTemp + 4].InnerText, out oddsLose))
                        {
                            oddsTableRecorder.OddsLose = oddsLose;
                        }

                        if ((oddsWin > 0 && oddsDraw > 0 && oddsLose > 0) || indexInIssueItem == 1)
                        {
                            oddsTableRecorderSet.Add(oddsTableRecorder);
                        }

                        oddsTableRecorderSet.Add(oddsTableRecorder);

                        indexTemp++;
                    }
                }
            }
        }
    }
    */
}
